package com.sanshow.charging.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.VideoView;

import com.google.android.exoplayer2.MediaItem;
import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.ui.PlayerView;
import com.google.android.exoplayer2.upstream.DataSpec;
import com.google.android.exoplayer2.upstream.FileDataSource;
import com.google.android.exoplayer2.upstream.RawResourceDataSource;
import com.sanshow.charging.MainActivity;
import com.sanshow.charging.MyApplication;
import com.sanshow.charging.R;
import com.sanshow.charging.util.GlideImageLoader;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class VideoFragment extends BaseFragment {

    private PlayerView playerView;
    public SimpleExoPlayer player;
    public ImageView imageView;
    public MediaPlayer mediaPlayer;
    private Bitmap bitmap;
    public List<String> allDataFileName;
    private static int i = 0; // 播放索引

    public Banner banner;

    private static String VIDEO_ROTATION_IMGPATH = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath() + "/sanshow/images/videoimgs/";
    private static String VIDEO_DOWNLOADPATH = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath() + "/sanshow/videos/";
    private static String VIDEO_DEFAULT_PATH = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath() + "/sanshow/default/logo.mp4";


    public VideoFragment() {
    }

    public static VideoFragment newInstance() {
        VideoFragment fragment = new VideoFragment();
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_video, container, false);

        playerView  = view.findViewById(R.id.playerView);
        banner = (Banner) view.findViewById(R.id.banner_top);

        initBanner();
        initVideo();
        return view;
    }

    private void initBanner() {
        // 设置轮播间隔时间
        banner.setDelayTime(5000);
        // 设置指示器的位置，小点点，左中右
        banner.setBannerStyle(BannerConfig.NOT_INDICATOR);
        //设置轮播的动画效果，内含多种特效，可点入方法内查找后内逐一体验
        banner.setBannerAnimation(Transformer.Accordion);

        // 本地图片数据（资源文件）
        List<String> list = getAllDataFileName(VIDEO_ROTATION_IMGPATH);
        if (list != null && !list.isEmpty()) {
            banner.setImages(list)
                    .setImageLoader(new GlideImageLoader())
                    .start();
        } else {
            List<Integer> localList = new ArrayList<>();
            localList.add(R.mipmap.logo);
            banner.setImages(localList)
                    .setImageLoader(new GlideImageLoader())
                    .start();
        }

    }

    private void initVideo() {
        int i = 0;
        allDataFileName = getAllDataFileName(VIDEO_DOWNLOADPATH);
        if (allDataFileName.size() > 0) {
            // 本地数据
            initializePlayerForSD();
        } else {
            // 默认项目内视频
            initializePlayerForDefaultVideo();
        }
    }

    /*private void initializePlayerForRaw() {
        RawResourceDataSource rawSource = new RawResourceDataSource(getActivity());
        try {
            rawSource.open(new DataSpec(RawResourceDataSource.buildRawResourceUri(R.raw.logo)));
        } catch (RawResourceDataSource.RawResourceDataSourceException e) {
            e.printStackTrace();
        }

        player = new SimpleExoPlayer.Builder(getActivity()).build();
        playerView.setPlayer(player);
        player.setMediaItem(MediaItem.fromUri(rawSource.getUri()));
        player.setRepeatMode(Player.REPEAT_MODE_ALL);
        player.prepare();
        player.play();
    }*/

    private void initializePlayerForDefaultVideo() {
        Uri videoUri = Uri.parse(VIDEO_DEFAULT_PATH);
        FileDataSource fileDataSource = new FileDataSource();
        try {
            fileDataSource.open(new DataSpec(videoUri));
        }catch (FileDataSource.FileDataSourceException e){
            e.printStackTrace();
        }

        player = new SimpleExoPlayer.Builder(getActivity()).build();
        playerView.setPlayer(player);
        player.setMediaItem(MediaItem.fromUri(fileDataSource.getUri()));
        player.setRepeatMode(Player.REPEAT_MODE_ALL);
        player.prepare();
        player.play();
    }

    private void initializePlayerForSD() {

        allDataFileName = getAllDataFileName(VIDEO_DOWNLOADPATH);
        Uri videoUri = Uri.parse(allDataFileName.get(0));
        FileDataSource fileDataSource = new FileDataSource();
        try {
            fileDataSource.open(new DataSpec(videoUri));
        }catch (FileDataSource.FileDataSourceException e){
            e.printStackTrace();
        }

        player = new SimpleExoPlayer.Builder(getActivity()).build();
        playerView.setPlayer(player);
        player.setMediaItem(MediaItem.fromUri(fileDataSource.getUri()));
        player.setRepeatMode(Player.REPEAT_MODE_ALL);
        player.prepare();
        player.play();
    }

    /*public void onCompletion(MediaPlayer mp) {
        if (allDataFileName.size() == 1) {
            videoView.setVideoURI(Uri.parse(allDataFileName.get(0)));
            videoView.start();
        } else {
            videoView.setVideoURI(Uri.parse(allDataFileName.get(i)));
            videoView.start();
            i++;
            if (i == allDataFileName.size()) {
                i = 0;
            }
        }
    }*/

    // 获取目录下的所有文件夹
    public List<String> getAllDataFileName(String filePath) {
        List<String> fileList = new ArrayList<>();

        File file = new File(filePath);
        File[] tempList = file.listFiles();
        if (tempList != null && tempList.length > 0) {
            for (int i = 0; i < tempList.length; i++) {
                if (tempList[i].isFile()) {
                    System.out.println("文     件：" + tempList[i].getName());
                    // tempList[i].toString();// 路径
                    // tempList[i].getName();// 文件名
                    // 文件名
                    String fileName = filePath + tempList[i].getName();
                    fileList.add(fileName);
                }
            }
        }
        return fileList;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        Log.e("Video-Fragment","banner、player资源已释放");
        banner.releaseBanner();
        player.release();
    }
}